<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称:" style="margin-bottom: 0px">
        <el-input v-model="keyword" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px">
        <el-button
          type="primary"
          size="default"
          :disabled="keyword.trim() ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button size="default" @click="reset">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin: 10px 0px">
    <el-button
      v-has="`btn.Role.add`"
      type="primary"
      size="default"
      icon="Plus"
      @click="addRole"
    >
      添加角色
    </el-button>
    <el-table :data="allRole" border style="margin: 10px 0px">
      <el-table-column
        label="#"
        type="index"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column
        label="id"
        width="120"
        align="center"
        prop="id"
      ></el-table-column>
      <el-table-column
        label="角色名称"
        width="350"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="400" align="center">
        <template #default="{ row, $index }">
          <el-button
            v-has="`btn.Role.assgin`"
            type="primary"
            size="small"
            icon="User"
            @click="setPermission(row)"
          >
            分配权限
          </el-button>
          <el-button
            v-has="`btn.Role.update`"
            type="primary"
            size="small"
            icon="Edit"
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            width="300px"
            :title="`确定要删除角色 ${row.roleName} 吗？`"
            @confirm="removeRole(row.id)"
          >
            <template #reference>
              <el-button
                v-has="`btn.Role.remove`"
                type="primary"
                size="small"
                icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[2, 3, 5, 10, 20, 50]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @current-change="getHasRole"
      @size-change="sizeChange"
    />
  </el-card>

  <!-- 添加或修改角色对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="roleParams.id ? '更新角色' : '添加角色'"
    :close-on-click-modal="false"
  >
    <el-form ref="ruleFormRef" :model="roleParams" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleParams.roleName" placeholder="请输入角色名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveRole(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 抽屉组件：分配角色的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配权限</h4>
    </template>
    <template #default>
      <el-tree
        ref="tree"
        style="max-width: 600px"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectArr"
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">
          取消
        </el-button>
        <el-button type="primary" @click="handler">
          确定
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
  reqRemoveRole
} from '@/api/acl/role'
import type {
  RoleResponseData,
  Records,
  RoleData,
  MenuResponseData,
  MenuList
} from '@/api/acl/role/type'
//获取设置相关的小仓库
import useLayoutSettingStore from '@/store/modules/setting'

const layoutSettingStore = useLayoutSettingStore()

const drawer = ref<boolean>(false)

const pageNo = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(100)

const keyword = ref<string>('')
//存储全部已有的角色
const allRole = ref<Records>([])

//定义数组存储用户权限的数据
const menuArr = ref<MenuList>([])

//数组用于存储勾选的节点的ID(四级)
const selectArr = ref<number[]>([])
//获取tree组件的实例
const tree = ref<any>()

//树形控件
const defaultProps = {
  children: 'children',
  label: 'name'
}

//控制对话框的显示与隐藏
const dialogFormVisible = ref<boolean>(false)

//收集新增角色数据
const roleParams = reactive<RoleData>({
  roleName: ''
})

const ruleFormRef = ref<FormInstance>()

const validateRoleName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('角色名称至少2位'))
  }
}

const rules = reactive<FormRules<typeof roleParams>>({
  roleName: [{ required: true, validator: validateRoleName, trigger: 'blur' }]
})

const saveRole = async (formEl: FormInstance | undefined) => {
  //先校验
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      //添加或更新职位
      const result: any = await reqAddOrUpdateRole(roleParams)
      if (result.code == 200) {
        ElMessage({
          type: 'success',
          message: roleParams.id ? '更新成功！' : '添加成功！'
        })
        dialogFormVisible.value = false
        if (roleParams.id) {
          keyword.value = ''
        }
        getHasRole(roleParams.id ? pageNo.value : 1)
      }
    } else {
      console.log('error submit!')
    }
  })
}

onMounted(() => {
  getHasRole()
})

const getHasRole = async (pager = 1) => {
  pageNo.value = pager
  const result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
  if (result.code == 200) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}

const sizeChange = () => {
  getHasRole()
}

//搜索按钮的回调
const search = () => {
  getHasRole()
  // keyword.value = ''
}

//重置按钮
const reset = () => {
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

//添加职位按钮的回调
const addRole = () => {
  //清空校验规则
  ruleFormRef.value?.clearValidate()
  //清空数据
  Object.assign(roleParams, {
    id: 0,
    roleName: ''
  })
  dialogFormVisible.value = true
}

//编辑按钮
const updateRole = (row: RoleData) => {
  dialogFormVisible.value = true
  //清空校验规则
  ruleFormRef.value?.clearValidate()
  Object.assign(roleParams, row)
}

//分配权限按钮
const setPermission = async (row: RoleData) => {
  //清空数据
  selectArr.value = []

  //收集当前要分配权限的角色的数据
  Object.assign(roleParams, row)
  //发请求
  const result: MenuResponseData = await reqAllMenuList(roleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }

  drawer.value = true
}

const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      //递归
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}

//抽屉确定按钮
const handler = async () => {
  //角色ID
  const roleId = roleParams.id as number
  //选中节点的ID
  const arr = tree.value.getCheckedKeys()
  //半选中状态的ID
  const arr1 = tree.value.getHalfCheckedKeys()
  //下发相应的请求
  const permissionId = arr.concat(arr1)
  const result: any = await reqSetPermission(roleId, permissionId)
  if (result.code == 200) {
    //抽屉关闭
    drawer.value = false
    ElMessage({
      type: 'success',
      message: '分配权限成功！'
    })
    //页面刷新
    window.location.reload()
  }
}

//删除已有的角色
const removeRole = async (roleId: number) => {
  const result: any = await reqRemoveRole(roleId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除角色成功！'
    })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
